<template>
  <div class="login-container">
    <background-particles />
    <n-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      label-placement="left"
      size="small"
      class="login-form"
    >
      <div class="lang-select">
        <g-lang-select />
      </div>

      <n-form-item path="title">
        <h2 class="title">战  情  中  心</h2>
      </n-form-item>

      <n-form-item path="username">
        <n-input
          v-model:value="loginForm.username"
          placeholder="用户名"
          type="text"
          size="large"
          :style="inputCSSVars"
        >
          <template #prefix>
            <n-icon>
              <IconUser />
            </n-icon>
          </template>
        </n-input>
      </n-form-item>
      <n-form-item path="password">
        <n-tooltip :show="capsTooltip" placement="top-start">
          <template #trigger>
            <n-input
              v-model:value="loginForm.password"
              placeholder="请输入密码"
              type="password"
              size="large"
              show-password-toggle
              :style="inputCSSVars"
              @keydown="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <n-icon>
                  <IconKey />
                </n-icon>
              </template>
            </n-input>
          </template>
          <span> 大写锁定已打开 </span>
        </n-tooltip>
      </n-form-item>
      <n-button
        :loading="loading"
        type="primary"
        size="large"
        style="width: 100%; margin-bottom: 20px"
        @click="handleLogin"
      >
        {{ $t("login.login") }}
      </n-button>
      <!-- <div style="position: relative;">
        <div class="tips">
          <span>{{ $t('login.username') }}: admin</span>
          <span>{{ $t('login.password') }}: 123123</span>
        </div>
      </div> -->
    </n-form>
  </div>
</template>

<script lang='ts'>
import { defineComponent, ref, watch, defineAsyncComponent } from "vue";
import { useRouter, useRoute } from "vue-router";
import { UserStore } from "@/domains/user";
import { IconUser, IconKey } from "@/icons";

const validateUsername = (rule: any, value: string, callback: Function) => {
  if (!["admin", "editor"].includes(value)) {
    callback(new Error("请输入正确的用户名"));
  } else {
    callback();
  }
};

const validatePassword = (rule: any, value: string, callback: Function) => {
  if (value.length < 6) {
    callback(new Error("密码不能少于6位"));
  } else {
    callback();
  }
};

const getOtherQuery = (query: any) => {
  return Object.keys(query).reduce((acc: any, cur) => {
    if (cur !== "redirect") {
      acc[cur] = query[cur];
    }
    return acc;
  }, {});
};

export default defineComponent({
  name: "Login",
  components: {
    BackgroundParticles: defineAsyncComponent(
      () => import("./background-particles.vue")
    ),
    live2d: defineAsyncComponent(() => import("./live2d.vue")),
    IconUser,
    IconKey,
  },
  setup() {
    const loginForm = ref({
      username: "admin",
      password: "123123",
    });

    const loginRules = ref({
      username: [
        { required: true, trigger: "blur", validator: validateUsername },
      ],
      password: [
        { required: true, trigger: "blur", validator: validatePassword },
      ],
    });

    const loginFormRef = ref(null);
    const capsTooltip = ref(false);
    const loading = ref(false);
    const redirect = ref("");
    const otherQuery = ref({});

    const inputCSSVars = {
      "--caret-color": "#fff",
      "--text-color": "#fff",
      "--border": "1px solid rgba(255, 255, 255, 0.3)",
      "--color": "transparent",
      "--color-focus": "transparent",
      "--color-focus-error": "transparent",
      "--color-focus-warning": "transparent",
    };

    const route = useRoute();
    const router = useRouter();

    watch(
      route,
      ({ query }) => {
        if (query) {
          redirect.value = query.redirect as string;
          otherQuery.value = getOtherQuery(query);
        }
      },
      { immediate: true }
    );

    const checkCapslock = ({ shiftKey, key }: any) => {
      if (key && key.length === 1) {
        if (
          (shiftKey && key >= "a" && key <= "z") ||
          (!shiftKey && key >= "A" && key <= "Z")
        ) {
          capsTooltip.value = true;
        } else {
          capsTooltip.value = false;
        }
      }

      if (key === "CapsLock" && capsTooltip.value === true) {
        capsTooltip.value = false;
      }
    };

    const handleLogin = () => {
      (loginFormRef.value as any).validate((errors: any) => {
        if (!errors) {
          loading.value = true;
          UserStore()
            .doLogin(loginForm.value.username, loginForm.value.password)
            .then(() => {
              router.push({
                path: redirect.value || "/",
                query: otherQuery.value,
              });
            })
            .finally(() => {
              loading.value = false;
            });
        }
      });
    };

    return {
      loginForm,
      loginRules,
      loginFormRef,
      capsTooltip,
      loading,
      redirect,
      otherQuery,
      inputCSSVars,
      checkCapslock,
      handleLogin,
    };
  },
});
</script>

<style lang="scss">
.login-container {
  width: 100%;
  min-height: 100%;
  height: 100vh;
  overflow: hidden;
  margin: 0 auto;
  background-color: #111222;
  .title {
    font-size: 34px;
    /* color: #eee; */
    color: rgba(255, 255, 255, 0.8);
    margin: 0px auto 0px auto;
    text-align: center;
    font-weight: bold;
  }

  .login-form {
    position: relative;
    width: 480px;
    max-width: 100%;
    padding: 0 30px;
    margin: 0 auto;
    margin-top: 18%;
    overflow: hidden;
  }

  .tips {
    margin-bottom: 10px;
    font-size: 14px;
    color: #fff;

    span {
      margin-right: 16px;
    }
  }

  .lang-select {
    float: right;
    margin-top: -24px;
    cursor: pointer;
    color: #bcc9d4;
  }
}
</style>
